using DL.Character.Core.Base.Movement;
using DL.Characters.Player;
using UnityEngine;

namespace DL.Movement
{
    /// <summary>
    /// 自定义位移控制器
    /// </summary>
    public class CustomMovementController : MonoBehaviour
    {
        protected Transform Self;
        protected PlayerMoveController MoveController;

        //Runtime Args
        protected bool CanMove;
        private AnimationCurve m_Curve;
        private int m_MoveAxis;
        private float m_Duration;
        private float m_LastDis;
        private Vector3 m_StartPos;
        private Vector3 m_MoveDir;
        private float m_StartTimer;
        public void Init(Player actor)
        {
            Self = actor.Self;
            MoveController = actor.MovementController;
        }

        public void CustomMovementMethod(CustomMovementSet data)
        {
            InterruptCustomMovement();
            SetMovement(data.customMovementCurve, data.moveAxis);
        }

        //提供一个简单版本
        public void CustomMovementMethod(AnimationCurve curve, int moveAxis)
        {
            InterruptCustomMovement();
        }


        public void InterruptCustomMovement()
        {
            CanMove = false;
            // MoveController.CharacterMoveInterface(Self.forward, 0, false);
        }
        
        // 初始化移动参数
        public void SetMovement(AnimationCurve curve, int moveAxis)
        {
            this.m_Curve = curve;
            this.m_MoveAxis = moveAxis;
            this.m_Duration = curve.keys[curve.length - 1].time;
            this.m_LastDis = 0f;
            this.m_StartPos = Self.position;
            this.m_MoveDir = Vector3.zero;
            switch (moveAxis)
            {
                case 0:
                    m_MoveDir = Self.forward;
                    break;
                case 1:
                    m_MoveDir = Self.right;
                    break;
                case 2:
                    m_MoveDir = Self.up;
                    break;
            }
            this.m_StartTimer = Time.time;
            CanMove = true;
        }

        private void FixedUpdate()
        {
            if(!CanMove) return;
            if (Time.time - m_StartTimer < m_Duration)
            {
                float num = m_Curve.Evaluate(Time.time - m_StartTimer);
                float num2 = (num * 10000f - m_LastDis * 10000f) / 10000f;
                if (m_MoveAxis != 2)
                {
                    MoveController.CharacterMoveInterface(m_MoveDir, num2 / Time.fixedDeltaTime, false);
                }
                else
                {
                    MoveController.CharacterVerticalVelocityInterface(num2);
                }
                m_LastDis = num;
            }
            else
            {
                Debug.Log("退出自定义位移，位移距离应为：" + m_Curve.Evaluate(m_Duration) + "---但实际位移应该是：" + (transform.position - m_StartPos).magnitude);
                CanMove = false;
            }
        }
        
        
    }
}
